<?php
	header("Cache-Control: no-cache");
	require_once "../includes/functions.php";
    $current_page = (is_numeric($_GET['page'])?$_GET['page']:1);
	$search_id = update_search_term($_GET['q'],$current_page);

    $query = urlencode($_GET['q']);
	switch ($_GET['type']) {
		case "Title":
			$bquery = "(TI+(".$query."))"; break;
		case "Author":
			$bquery = "(AU+(".$query."))"; break;
		default:
			$bquery = "(TX+(".$query."))";
	}
    $bquery .= "+and+(FT+Y)";
    
    if ($_GET['source']=="gadget") { $startrec=1; $endrec=5; $gadget=true; }
    else if ($_GET['source']=="mobile") { $startrec = ($current_page-1)*5+1; $endrec = $startrec+5; $mobile=true; }
    else { $startrec = ($current_page-1)*10+1; $endrec = $startrec+9; }
	
    $url = "http://eit.ebscohost.com/Services/SearchService.asmx/Search?prof=EBSCO_DETAILS_REMOVED"
         . "&startrec={$startrec}&sort=Relevance&query=$bquery";
         //echo $url;
    $result_xml = curl_get_url($url);
    preg_match('/<Hits xmlns=".+?">(.+?)<\\/hits>/i',$result_xml,$hits);
    preg_match_all('/<rec recordID="[0-9]+?">(.+?)<\\/rec>/is',$result_xml,$results);
    
    $total_pages = ceil($hits[1]/10);
    
    if (count($results[1])==0) { exit("<b>There are no results for your search, please try again with fewer or less specific keywords.</b>"); }
    
  	if (!$gadget && !$mobile) { echo "<a style=\"padding-top:10px;margin-top:-15px;\" id=\"search-results\"><span style=\"font-size:13px;\">Search results $startrec-$endrec of {$hits[1]} for: <span style=\"font-weight:bold;\">{$_GET['q']}</span> in <span style=\"font-weight:bold;\">{$_GET['type']}</span><br/><br style=\"font-size:6px;\"/></a>\n"; }
    if ($mobile) { echo "<input type=\"hidden\" id=\"search-id\" value=\"{$search_id}\"/>"; }

    $result_number=1;

    foreach ($results[1] as $val) {
    //echo "<pre>".htmlentities($val)."</pre>";
        if (($gadget) && ($result_number>5)) break;                             # Only show 5 results for the gadget...
        preg_match('/<atl>(.+?)<\\/atl>/is',$val,$title);                       # Resource Title
        preg_match('/<plink>(.+?)<\\/plink>/i',$val,$url);                      # URL
        preg_match('/dt year="(.+?)" month="(.+?)" day="(.+?)">/i',$val,$date); # Date
        preg_match_all('/<au>(.+?)<\\/au>/i',$val,$authors);                    # Authors
        preg_match_all('/<subj type="thes">(.+?)<\\/subj>/i',$val,$subjects);   # Subjects
        preg_match('/<jtl>(.+?)<\\/jtl>/i',$val,$journal_title);                # Journal Title
        preg_match('/<issn>(.+?)<\\/issn>/i',$val,$issn);                       # ISSN
        preg_match('/<vid>(.+?)<\\/vid>/i',$val,$vol);                          # - Volume
        preg_match('/<iid>(.+?)<\\/iid>/i',$val,$issue);                        # - Issue
        preg_match('/<ui type="doi">(.+?)<\\/ui>/i',$val,$doi);                 # DOI
        $str_date = $months[$date[2]-1] . " " . $date[1];
        $proxyurl = ezproxy_url($url[1]);
        
        $dispatch_url = "/rise/dispatch.php?type=search&search_id={$search_id}&result_number={$result_number}"
					  . "&issn={$issn[1]}&vol={$vol[1]}&issue={$issue[1]}&doi={$doi[1]}&name=".urlencode($title[1])."&url=";

        if ($gadget) {
            echo "<p style=\"font-size:12px;margin:2px;\">{$result_number}: <a target=\"_blank\" title=\"{$title[1]}\" href=\"$dispatch_url".urlencode($url[1])."\">".ssreplace($title[1],40)."</a></p>";
        }
        else if ($mobile) { if ($result_number<6) {
            echo "<p class=\"search-result\"><a target=\"_blank\"".generate_link($proxyurl)."><span class=\"pointer\" style=\"text-decoration:none;\">&#0187;</span>".ssreplace(ucwords(strtolower($title[1])),38)."<br/>"
               . "<span>Date: $str_date".(!empty($authors[1])?" <span style=\"font-weight:bold\">/</span> Author(s): ".ssreplace(implode(" / ",$authors[1]),20):"")
               . "</span></a></p>";
        } }
        else {
            echo "<script type=\"text/javascript\">_gaq.push(['_trackPageview','/search']);</script>\n";
            echo "<p style=\"margin-top:-2px;\"><a class=\"search-result\" style=\"\" target=\"_blank\"".generate_link($dispatch_url.urlencode($proxyurl)).">" . ssreplace($title[1],115) . "</a><br/>"
                 . "<span style=\"color:#676767;font-size:11px;\">Date: $str_date".(!empty($authors[1])?" <span style=\"font-weight:bold;\">/</span> Author(s): " . ssreplace(implode(" / ",$authors[1]),50):"")
                 . (!empty($journal_title[1])?"&nbsp;<span style=\"font-weight:bold;\">/</span>&nbsp;Source: " . ssreplace($journal_title[1],58) . " Vol. {$vol[1]} Issue {$issue[1]}":"")
                 . "</span></p>\n";
        }
        $result_number++;
    }
    
    if ($gadget) {
        $more_href = "http://library.open.ac.uk/rise/?query=".$query."&searchBy=".$_GET['type'];
        echo "<a target=\"_blank\" href=\"{$more_href}\" style=\"font-style:italic;\" href=\"#\">More Results &#0187;</a>";
    } else {
        $previous_page_style = ($current_page-1<1?"color:#AAAAAA;cursor:text;":"");
        $next_page_style = ($current_page+1>$total_pages?"color:#AAAAAA;cursor:text;":"");

        //-- generate "Users searching for x, most often visited:" recommendations"
        $search_rec_q = "SELECT resources.name,resources.url,resources.id,search_id,resources.ISSN FROM resource_search_relationships "
                      . "JOIN resources ON resources.id=resource_id "
                      . "WHERE search_id={$search_id} AND url!='' ORDER BY value DESC LIMIT 4";
        //echo $search_rec_q;
        $search_rec_q = @mysql_query($search_rec_q) or die(mysql_error());
        
        if ((@mysql_num_rows($search_rec_q)>0) && (!$mobile)) {
            echo "<fieldset class=\"search-recs\" style=\"margin-bottom:8px;\"><legend style=\"font-weight:bold;\">People using similar search terms often viewed:</legend>";
            echo "  <ol>";
            while ($temp=@mysql_fetch_assoc($search_rec_q)) {
                # Need to send this through the dispatcher
                echo "<li><a target=\"_blank\" class=\"search-rec\" rank=\"search_".(++$searchrank)."\" id=\"{$temp['id']}\" searchid=\"{$search_id}\"".generate_link($temp['url']).">".ssreplace($temp['name'],115)."</a></li>";
            }
            echo "  </ol>";
            echo "</fieldset>";
        }
        if ($mobile) {
            echo "<div id=\"pagination\">"
               . "    <div class=\"page-nav\">";
            if ($current_page-1>0) { echo "<a id=\"".($current_page-1)."\" href=\"#\" title=\"Next Page (".($current_page+1)."\"><span class=\"page-pointer\">&#0171;</span> Previous</a>\n"; }
            else { echo "<span class=\"page-pointer\">&#0171;</span> Previous\n"; }
            echo "    </div>";
            
            if ($total_pages>10000) $total_pages_text = '1000+';
            echo "    <div class=\"page-info\">"
               . "&nbsp;&nbsp;Page <b>$current_page</b> of <b>{$total_pages_text}</b>&nbsp;&nbsp;"
               . "    </div>";
            
            echo "    <div class=\"page-nav\">";
            if ($current_page+1<=$total_pages) { echo "<a id=\"".($current_page+1)."\" href=\"#\" title=\"Next Page (".($current_page+1).")\">Next <span class=\"page-pointer\">&#0187;</span></a>"; }
            else { echo "Next <span class=\"page-pointer\">&#0187;</span>\n"; }
            echo "    </div>";
            echo "</div>\n";
        }
        else {
            echo "<div id=\"pagination\">";
            if ($current_page-1>0) { echo "<a id=\"".($current_page-1)."\" href=\"#\" title=\"Next Page (".($current_page+1)."\"><img src=\"/rise/images/previous.jpg\" alt=\"Previous\"/></a>\n"; }
            else { echo "<img src=\"/rise/images/previousdisabled.jpg\" alt=\"\"/>\n"; }
            
            echo "&nbsp;&nbsp;Page <b>$current_page</b> of <b>{$total_pages}</b>&nbsp;&nbsp;";
            
            if ($current_page+1<=$total_pages) { echo "<a id=\"".($current_page+1)."\" href=\"#\" title=\"Next Page (".($current_page+1).")\"><img src=\"/rise/images/next.jpg\" alt=\"Next\"/></a>"; }
            else { echo "<img src=\"/rise/images/nextdisabled.jpg\" alt=\"\"/>\n"; }
            echo "</div>\n";
        }
    }
    echo "<script type=\"text/javascript\">pageTracker._trackPageview('/search.php');</script>\n";
           
    
?>